<script setup lang="ts">
import { ref, onMounted } from 'vue'
import AppHeader from '@/components/layout/AppHeader.vue'
import LeftSidebar from '@/components/layout/LeftSidebar.vue'
import { HOME_SECTIONS, type HomeSection } from '@/constants/HOME'
import { useAuthStore } from '@/stores/auth'
import { api, toAbsoluteUrl } from '@/utils/request'

const auth = useAuthStore()
const currentSection = ref<HomeSection>(HOME_SECTIONS.HOME)

const activeTab = ref<'profile' | 'recharge' | 'withdraw'>('profile')
const balance = ref<string>('0')
const recharges = ref<any[]>([])
const withdrawals = ref<any[]>([])

async function fetchWallet() {
  try {
    const res = await api.get('/api/pay/wallet')
    if (res.ok) {
      const data = await res.json()
      balance.value = String(data?.balancePoints ?? '0')
    }
  } catch {}
}
async function fetchRecharges() {
  try {
    const res = await api.get('/api/pay/recharges')
    if (res.ok) recharges.value = await res.json()
  } catch {}
}

async function fetchWithdrawals() {
  try {
    const res = await api.get('/api/pay/withdrawals')
    if (res.ok) withdrawals.value = await res.json()
  } catch {}
}

onMounted(async () => {
  // 总是刷新用户信息以确保数据最新
  await auth.refreshUserInfo()

  // 如果已登录，则获取相关数据
  if (auth.user) {
    await Promise.all([fetchWallet(), fetchRecharges(), fetchWithdrawals()])
  }
})

function statusText(s: string) {
  switch (s) {
    case 'approved':
      return '승인됨'
    case 'rejected':
      return '거부됨'
    default:
      return '심사 중'
  }
}

// 表单状态：编辑资料
const formProfile = ref<{ name: string; nickname: string; phone: string; gender: string; birthdate: string }>({
  name: '',
  nickname: '',
  phone: '',
  gender: '',
  birthdate: '',
})
const savingProfile = ref(false)

// 表单状态：修改密码
const formPwd = ref<{ currentPassword: string; newPassword: string; confirm: string }>({
  currentPassword: '',
  newPassword: '',
  confirm: '',
})
const savingPwd = ref(false)

// 头像上传
const avatarFile = ref<File | null>(null)
const avatarPreview = ref<string>('')
const uploadingAvatar = ref(false)

function fmtYmd(d: Date) {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

function initFormsFromUser() {
  const u = auth.user
  if (!u) return
  formProfile.value.name = u.name || ''
  formProfile.value.nickname = u.nickname || ''
  formProfile.value.phone = u.phone || ''
  formProfile.value.gender = (u.gender as string) || ''
  const bd = u.birthdate as string | null | undefined
  formProfile.value.birthdate = bd ? fmtYmd(new Date(bd)) : ''
}

async function onSaveProfile() {
  try {
    savingProfile.value = true
    const payload: { name: string | null; nickname: string | null; phone: string | null; gender: string | null; birthdate: string | null } = {
      name: formProfile.value.name || null,
      nickname: formProfile.value.nickname || null,
      phone: formProfile.value.phone || null,
      gender: formProfile.value.gender || null,
      birthdate: formProfile.value.birthdate || null,
    }
    const res = await api.put('/api/auth/me/profile', payload)
    if (!res.ok) {
      const err = await res.json().catch(() => ({}))
      throw new Error(err?.error || '프로필 저장 실패')
    }
    await auth.fetchMe()
    initFormsFromUser()
    alert('프로필이 저장되었습니다')
  } catch (e) {
    const msg = e instanceof Error ? e.message : '프로필 저장 실패'
    alert(msg)
  } finally {
    savingProfile.value = false
  }
}

async function onChangePassword() {
  if (formPwd.value.newPassword.length < 8) {
    alert('새 비밀번호는 최소 8자입니다')
    return
  }
  if (formPwd.value.newPassword !== formPwd.value.confirm) {
    alert('새 비밀번호가 일치하지 않습니다')
    return
  }
  try {
    savingPwd.value = true
    const res = await api.put('/api/auth/me/password', {
      currentPassword: formPwd.value.currentPassword,
      newPassword: formPwd.value.newPassword,
    })
    if (!res.ok) {
      const err = await res.json().catch(() => ({}))
      throw new Error(err?.error || '비밀번호 변경 실패')
    }
    formPwd.value.currentPassword = ''
    formPwd.value.newPassword = ''
    formPwd.value.confirm = ''
    alert('비밀번호가 성공적으로 변경되었습니다')
  } catch (e) {
    const msg = e instanceof Error ? e.message : '비밀번호 변경 실패'
    alert(msg)
  } finally {
    savingPwd.value = false
  }
}

function onPickAvatar(ev: Event) {
  const input = ev.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return
  avatarFile.value = file
  avatarPreview.value = URL.createObjectURL(file)
}

async function onUploadAvatar() {
  if (!avatarFile.value) {
    alert('먼저 이미지 파일을 선택하세요')
    return
  }
  try {
    uploadingAvatar.value = true
    const fd = new FormData()
    fd.append('avatar', avatarFile.value)
    const up = await api.post('/api/auth/me/avatar/upload', fd)
    if (!up.ok) {
      const err = await up.json().catch(() => ({}))
      throw new Error(err?.error || '프로필 이미지 업로드 실패')
    }
    const data = await up.json()
    const setRes = await api.put('/api/auth/me/avatar', { avatarUrl: data?.avatarUrl })
    if (!setRes.ok) {
      const err = await setRes.json().catch(() => ({}))
      throw new Error(err?.error || '프로필 이미지 설정 실패')
    }
    await auth.fetchMe()
    avatarFile.value = null
    avatarPreview.value = ''
    alert('프로필 이미지가 성공적으로 업데이트되었습니다')
  } catch (e) {
    const msg = e instanceof Error ? e.message : '프로필 이미지 업데이트 실패'
    alert(msg)
  } finally {
    uploadingAvatar.value = false
  }
}

// 会员等级相关
const MEMBER_LEVEL_NAMES = {
  regular: '일반회원',
  silver: '실버',
  gold: '골드',
  diamond: '다이아',
  vip: 'VIP'
}

function getMemberLevelName(level: string | undefined): string {
  if (!level) return '일반회원'
  return MEMBER_LEVEL_NAMES[level as keyof typeof MEMBER_LEVEL_NAMES] || '일반회원'
}

// 刷新用户信息
const refreshing = ref(false)
async function refreshUserInfo() {
  refreshing.value = true
  try {
    await auth.refreshUserInfo()
    if (auth.user) {
      await Promise.all([fetchWallet(), fetchRecharges(), fetchWithdrawals()])
    }
  } finally {
    refreshing.value = false
  }
}

// 初始化表单数据
onMounted(() => {
  initFormsFromUser()
})
</script>

<template>
  <div class="layout">
    <AppHeader />

    <!-- 未登录提示 -->
    <div v-if="!auth.user" class="login-prompt">
      <div class="prompt-card">
        <h2>개인 센터</h2>
        <p>로그인 후 개인정보, 충전 기록, 출금 기록 등을 확인할 수 있습니다</p>
        <div class="prompt-actions">
          <button class="btn-primary" @click="$router.push('/login')">지금 로그인</button>
          <button class="btn-secondary" @click="$router.push('/live')">먼저 라이브 보기</button>
        </div>
      </div>
    </div>

    <!-- 已登录内容 -->
    <div v-else class="main">
      <LeftSidebar v-model="currentSection" />
      <section class="right">
        <h2 class="title">내 페이지</h2>

        <div class="tabs">
          <button
            :class="['tab', { active: activeTab === 'profile' }]"
            @click="activeTab = 'profile'"
          >
            내 정보
          </button>
          <button
            :class="['tab', { active: activeTab === 'recharge' }]"
            @click="activeTab = 'recharge'"
          >
            충전 기록
          </button>
          <button
            :class="['tab', { active: activeTab === 'withdraw' }]"
            @click="activeTab = 'withdraw'"
          >
            출금 기록
          </button>
          <div class="spacer"></div>
          <div class="balance">
            포인트：<b>{{ balance }}</b>
          </div>
        </div>

        <div v-if="activeTab === 'profile'" class="profile-section">
          <!-- 프로필 표시 -->
          <div class="card">
            <div class="card-header">
              <h3>개인 정보</h3>
              <button class="refresh-btn" @click="refreshUserInfo" :disabled="refreshing">
                {{ refreshing ? '새로고침 중...' : '정보 새로고침' }}
              </button>
            </div>
            <div class="row"><span>사용자 ID</span><b>{{ auth.user?.id }}</b></div>
            <div class="row"><span>로그인 계정</span><b>{{ auth.user?.loginId }}</b></div>
            <div class="row"><span>이메일</span><b>{{ auth.user?.email || '-' }}</b></div>
            <div class="row"><span>회원 등급</span><b class="member-level">{{ getMemberLevelName(auth.user?.memberLevel) }}</b></div>
            <div class="row"><span>성명</span><b>{{ auth.user?.name || '-' }}</b></div>
            <div class="row"><span>닉네임</span><b>{{ auth.user?.nickname || '-' }}</b></div>
            <div class="row"><span>휴대폰 번호</span><b>{{ auth.user?.phone || '-' }}</b></div>
            <div class="row"><span>성별</span><b>{{ auth.user?.gender || '-' }}</b></div>
            <div class="row"><span>생일</span><b>{{ auth.user?.birthdate ? new Date(auth.user.birthdate).toLocaleDateString() : '-' }}</b></div>
            <div class="row" v-if="auth.user?.avatarUrl">
              <span>프로필 이미지</span>
              <b><img :src="toAbsoluteUrl(auth.user?.avatarUrl)" alt="avatar" class="avatar" /></b>
            </div>
          </div>

          <!-- 编辑资料 -->
          <div class="card">
            <h3 class="subtitle">프로필 편집</h3>
            <form class="form" @submit.prevent="onSaveProfile">
              <label class="form-row">
                <span>성명</span>
                <input v-model="formProfile.name" type="text" placeholder="성명을 입력하세요" />
              </label>
              <label class="form-row">
                <span>닉네임</span>
                <input v-model="formProfile.nickname" type="text" placeholder="닉네임을 입력하세요" />
              </label>
              <label class="form-row">
                <span>휴대폰 번호</span>
                <input v-model="formProfile.phone" type="tel" placeholder="휴대폰 번호를 입력하세요" />
              </label>
              <label class="form-row">
                <span>성별</span>
                <select v-model="formProfile.gender">
                  <option value="">설정 안함</option>
                  <option value="male">남성</option>
                  <option value="female">여성</option>
                  <option value="other">기타</option>
                </select>
              </label>
              <label class="form-row">
                <span>생일</span>
                <input v-model="formProfile.birthdate" type="date" />
              </label>
              <div class="form-actions">
                <button class="primary" type="submit" :disabled="savingProfile">프로필 저장</button>
              </div>
            </form>
          </div>

          <!-- 비밀번호 변경 -->
          <div class="card">
            <h3 class="subtitle">비밀번호 변경</h3>
            <form class="form" @submit.prevent="onChangePassword">
              <label class="form-row">
                <span>현재 비밀번호</span>
                <input v-model="formPwd.currentPassword" type="password" placeholder="현재 비밀번호를 입력하세요" />
              </label>
              <label class="form-row">
                <span>새 비밀번호</span>
                <input v-model="formPwd.newPassword" type="password" placeholder="최소 8자" />
              </label>
              <label class="form-row">
                <span>새 비밀번호 확인</span>
                <input v-model="formPwd.confirm" type="password" placeholder="새 비밀번호를 다시 입력하세요" />
              </label>
              <div class="form-actions">
                <button class="primary" type="submit" :disabled="savingPwd">비밀번호 변경</button>
              </div>
            </form>
          </div>

          <!-- 프로필 이미지 설정 (파일 업로드) -->
          <div class="card">
            <h3 class="subtitle">프로필 이미지 설정</h3>
            <div class="avatar-box">
              <img v-if="avatarPreview || (auth.user && auth.user.avatarUrl)" :src="avatarPreview || toAbsoluteUrl(auth.user?.avatarUrl)" class="avatar large" alt="avatar" />
              <div class="uploader">
                <input type="file" accept="image/*" @change="onPickAvatar" />
                <button class="primary" @click="onUploadAvatar" :disabled="uploadingAvatar || !avatarFile">업로드 및 저장</button>
              </div>
            </div>
          </div>
        </div>

        <div v-else-if="activeTab === 'recharge'" class="card">
          <table class="table">
            <thead>
              <tr>
                <th>생성 시간</th>
                <th>참조 번호</th>
                <th>포인트</th>
                <th>상태</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="r in recharges" :key="r.id">
                <td>{{ new Date(r.createdAt).toLocaleString() }}</td>
                <td>{{ r.referenceNo }}</td>
                <td>{{ r.pointsCredited }}</td>
                <td>{{ statusText(r.status) }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div v-else class="card">
          <table class="table">
            <thead>
              <tr>
                <th>생성 시간</th>
                <th>참조 번호</th>
                <th>포인트</th>
                <th>예상 입금액</th>
                <th>상태</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="w in withdrawals" :key="w.id">
                <td>{{ new Date(w.createdAt).toLocaleString() }}</td>
                <td>{{ w.referenceNo }}</td>
                <td>{{ w.pointsToWithdraw }}</td>
                <td>{{ w.amountDecimal }}</td>
                <td>{{ statusText(w.status) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>
    </div>
  </div>
</template>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-bg);
  color: var(--color-text);
}

.main {
  flex: 1;
  display: flex;
  min-height: 0;
}

/* 移动端响应式设计 */
@media (max-width: 480px) {
  .layout {
    padding-bottom: 80px; /* 为底部导航留出空间 */
  }

  .main {
    /* 在手机端，侧边栏变成固定定位，所以主内容区域占满宽度 */
    display: block;
  }
}

.login-prompt {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.prompt-card {
  background: white;
  border-radius: 12px;
  padding: 3rem;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  width: 100%;
}

.prompt-card h2 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.5rem;
}

.prompt-card p {
  color: #666;
  margin-bottom: 2rem;
  line-height: 1.6;
}

.prompt-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.btn-primary, .btn-secondary {
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-primary {
  background: #ff6b6b;
  color: white;
}

.btn-primary:hover {
  background: #ff5252;
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #dee2e6;
}

.btn-secondary:hover {
  background: #e9ecef;
}

.right {
  flex: 1;
  padding: var(--space-5);
  overflow: auto;
  background: var(--color-surface);
}

.title {
  margin: 0 0 var(--space-4);
  font-size: 28px;
  font-weight: 700;
  color: var(--color-text);
}

.tabs {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  margin-bottom: var(--space-5);
  padding: var(--space-1);
  background: var(--color-bg);
  border-radius: var(--radius-lg);
  border: 1px solid var(--color-border);
}

.tab {
  height: 40px;
  padding: 0 var(--space-4);
  border-radius: var(--radius-md);
  border: 1px solid transparent;
  background: transparent;
  color: var(--color-text-secondary);
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.tab:hover {
  background: var(--color-surface-hover);
  color: var(--color-text);
}

.tab.active {
  background: var(--color-primary-light);
  color: var(--color-primary);
  border-color: var(--color-primary);
}

.spacer {
  flex: 1;
}

.balance {
  color: var(--color-success);
  font-weight: 600;
  padding: var(--space-2) var(--space-3);
  background: rgba(16, 185, 129, 0.1);
  border-radius: var(--radius-md);
  border: 1px solid rgba(16, 185, 129, 0.2);
}

.card {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
  box-shadow: var(--shadow-sm);
  margin-bottom: var(--space-4);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-4);
  padding-bottom: var(--space-3);
  border-bottom: 1px solid var(--color-border-light);
}

.card-header h3 {
  margin: 0;
  color: var(--color-text);
  font-size: 1.25rem;
  font-weight: 600;
}

.refresh-btn {
  background: var(--color-primary);
  color: white;
  border: none;
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-md);
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
}

.refresh-btn:hover:not(:disabled) {
  background: var(--color-primary-dark);
  transform: translateY(-1px);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.member-level {
  color: var(--color-primary) !important;
  font-weight: 700 !important;
  padding: 2px 8px;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 4px;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-3) 0;
  border-bottom: 1px solid var(--color-border-light);
}

.row:last-child {
  border-bottom: 0;
}

.row span {
  color: var(--color-text-secondary);
  font-weight: 500;
}

.row b {
  color: var(--color-text);
  font-weight: 600;
}

.table {
  width: 100%;
  border-collapse: collapse;
  background: var(--color-bg);
  border-radius: var(--radius-md);
  overflow: hidden;
}

.table th {
  background: var(--color-surface);
  color: var(--color-text-secondary);
  font-weight: 600;
  padding: var(--space-3) var(--space-4);
  text-align: left;
  border-bottom: 1px solid var(--color-border);
}

.table td {
  padding: var(--space-3) var(--space-4);
  border-bottom: 1px solid var(--color-border-light);
  color: var(--color-text);
}

.table tr:hover {
  background: var(--color-surface-hover);
}

/* 我的信息增强样式 */
.profile-section {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.subtitle {
  margin: 0 0 var(--space-3);
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text);
}

.form {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.form-row {
  display: flex;
  gap: var(--space-3);
  align-items: center;
}

.form-row > span {
  width: 100px;
  color: var(--color-text-secondary);
  font-weight: 500;
}

.form-row input,
.form-row select {
  flex: 1;
  height: 44px;
  padding: 0 var(--space-3);
  border-radius: var(--radius-md);
  border: 1px solid var(--color-border);
  background: var(--color-bg);
  color: var(--color-text);
  font-size: 14px;
  transition: all 0.2s ease;
}

.form-row input:focus,
.form-row select:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
}

.form-row input::placeholder {
  color: var(--color-text-muted);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--space-2);
}

button.primary {
  height: 44px;
  padding: 0 var(--space-5);
  border-radius: var(--radius-md);
  border: none;
  background: var(--gradient-primary);
  color: var(--color-text-white);
  cursor: pointer;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

button.primary:hover {
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

button.primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.avatar {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 50%;
  border: 2px solid var(--color-border);
  box-shadow: var(--shadow-sm);
}

.avatar.large {
  width: 80px;
  height: 80px;
  border: 3px solid var(--color-border);
}

.avatar-box {
  display: flex;
  align-items: center;
  gap: var(--space-4);
  padding: var(--space-4);
  background: var(--color-surface);
  border-radius: var(--radius-md);
  border: 1px solid var(--color-border);
}

.uploader {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.uploader input[type='file'] {
  padding: var(--space-2);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  background: var(--color-bg);
  color: var(--color-text);
  font-size: 14px;
}

.uploader input[type='file']::-webkit-file-upload-button {
  background: var(--color-surface);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  padding: var(--space-1) var(--space-2);
  margin-right: var(--space-2);
  cursor: pointer;
}

.member-level {
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-sm);
  font-weight: 600;
  font-size: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
